package com.service.impl;

import com.entity.ElderInfo;
import com.repository.ElderInfoRepository;
import com.service.ElderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ElderInfoServiceImpl implements ElderInfoService {

    @Autowired
    private ElderInfoRepository elderInfoRepository;

    @Override
    public ElderInfo save(ElderInfo elderInfo) {
        return elderInfoRepository.save(elderInfo);
    }

    @Override
    public ElderInfo saveByIdCard(String idCard, ElderInfo elderInfo) {
        ElderInfo elderInfo1 = elderInfoRepository.findByIdCard(idCard);
        if (elderInfo1 != null) {
            elderInfo1.setCheckOutDate(elderInfo.getCheckOutDate());
            elderInfo1.setStatus(2);
            elderInfo1.setDischargeReason(elderInfo.getDischargeReason());
        }
        assert elderInfo1 != null;
        return elderInfoRepository.save(elderInfo1);

    }

    @Override
    public void deleteById(Integer id) {
        elderInfoRepository.deleteById(id);
    }

    @Override
    @Transactional
    public ElderInfo update(ElderInfo elderInfo) {
        return elderInfoRepository.save(elderInfo);
    }

    @Override
    @Transactional(readOnly = true)
    public ElderInfo findById(Integer id) {
        return elderInfoRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(readOnly = true)
    public ElderInfo findByIdCard(String idCard) {
        return elderInfoRepository.findByIdCard(idCard);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ElderInfo> findAll() {
        return elderInfoRepository.findAllByStatusIs(1);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<ElderInfo> findAll(PageRequest pageRequest) {
        return elderInfoRepository.findAll(pageRequest);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ElderInfo> findByName(String name) {
        return elderInfoRepository.findByElderNameContaining(name);
    }
}